
import { Cartesian3,Matrix4,Matrix3,Math,Color,HeadingPitchRoll,Transforms,Cesium3DTileset,HeightReference,ConstantProperty,Cartographic,BillboardGraphics,LabelGraphics,GeoJsonDataSource,PointGraphics,VerticalOrigin,Cartesian2,NearFarScalar} from 'cesium';
import * as Cesium from 'cesium';
import dragIconLight from './dragIconLight.png'
import swenicon from './s_swenz.png'
import sweiicon from './s_sweiz.png'
import skzicon from './s_skz.png'
//向场景中添加gltf模型
export const createModel = function(viewer,url,latlngheigt) {
    var position = Cartesian3.fromDegrees(latlngheigt.lng, latlngheigt.lat, latlngheigt.height);
    var heading = Math.toRadians(latlngheigt.heading||0);
    var pitch = Math.toRadians(latlngheigt.pitch||0);
    var roll = Math.toRadians(latlngheigt.roll||0);
    var hpr = new HeadingPitchRoll(heading, pitch, roll);
    var orientation = Transforms.headingPitchRollQuaternion(position, hpr);
    var entity = viewer.entities.add({
        name : url,
        position : position,
        orientation : orientation,
        model : {
            uri : url,
            scale:latlngheigt.scale || 1
            // minimumPixelSize : 128,
            // maximumScale : 20000
        }
    });
    // viewer.entities.add({
    //     id:latlngheigt.id,
    //     name: '',
    //     position: Cartesian3.fromDegrees(latlngheigt.lng, latlngheigt.lat,latlngheigt.height+20),
    //     // position: positions[positions.length - 1],
    //     point: {
    //         pixelSize: 5,
    //         color: Cesium.Color.RED,
    //         outlineColor: Cesium.Color.WHITE,
    //         disableDepthTestDistance:Number.POSITIVE_INFINITY,
    //         outlineWidth: 2,
    //     },
    //     label: {
    //         text: latlngheigt.title,
    //         font: '18px sans-serif',
    //         fillColor: Cesium.Color.GOLD,
    //         style: Cesium.LabelStyle.FILL_AND_OUTLINE,
    //         disableDepthTestDistance:Number.POSITIVE_INFINITY,
    //         outlineWidth: 2,
    //         verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
    //         pixelOffset: new Cesium.Cartesian2(20, -20),
    //     }
    // });
    viewer.zoomTo(entity)
    return entity
    // viewer.trackedEntity = entity;
}
//向场景中添加geojson
export const creatGeojsonLayer = function(viewer,url,type){
    var markstyle = {
        "PP":"",//雨量站
        "BB":"",//蒸发站
        "ZQ":"",//流量站
        "DD":swenicon,//水文站
        "ZZ":sweiicon,//河道水位站
        "TT":"",//潮位站
        "RR":skzicon,//水库站
        "DP":"",//泵站
    }
    return new Promise(function(resolve,reject){
        var promise = GeoJsonDataSource.load(url,{
            clampToGround:true,
            fill:new Color(1, 0.1, 0.1, 0.8) 
        });
        promise.then(function(dataSource) {
            viewer.dataSources.add(dataSource);
            var entities = dataSource.entities.values;
            for (var i = 0; i < entities.length; i++) {
                var entity = entities[i];
                var lableTxt = entity.properties._STNM.getValue() || entity.properties._Name.getValue();
                entity.billboard = undefined;
                if(type=="PP"){
                    entity.point = new PointGraphics({
                        color: new Color(0.1, 0.1, 0.6, 0.8),
                        outlineColor:new Color(1, 1, 1, 0.8),
                        outlineWidth:2,
                        pixelSize: 10,
                        // eyeOffset: new ConstantProperty(new Cartesian3(0, 0, -100)),
                        disableDepthTestDistance:Number.POSITIVE_INFINITY,
                        heightReference:HeightReference.CLAMP_TO_GROUND
                        // heightReference : Cesium.HeightReference.CLAMP_TO_GROUND,
                    });
                }
                else{
                    entity.billboard = new BillboardGraphics({
                        image:markstyle[type],
                        disableDepthTestDistance:Number.POSITIVE_INFINITY,
                        heightReference:HeightReference.CLAMP_TO_GROUND,
                        scale:0.6
                    })
                }
                // entity.label = new LabelGraphics({
                    // text:"雨量站",
                // })
                if(lableTxt){
                    var offsetX = lableTxt.length*8+12
                    entity.label = new LabelGraphics({
                        text:lableTxt,
                        font : '12px sans-serif',
                        fillColor :new Color(0.9, 0.9, 0.9, 0.9),
                        outlineWidth : 2,
                        showBackground:true,
                        backgroundColor:new Color(0.1, 0.1, 0.1, 0.8),
                        verticalOrigin : VerticalOrigin.BOTTOM,
                        pixelOffset : new Cartesian2(offsetX, 10),
                        scaleByDistance: new NearFarScalar(800000, 1, 1000000, 0),
                        disableDepthTestDistance:Number.POSITIVE_INFINITY,
                        heightReference:HeightReference.CLAMP_TO_GROUND
                    })
                }
            }
            // viewer.zoomTo(dataSource)
            viewer.flyTo(dataSource,{
                maximumHeight:0,
                offset : {
                    heading : Cesium.Math.toRadians(0.0),
                    pitch : Cesium.Math.toRadians(-90),
                    range : 0
                }
            });
            resolve(dataSource)
        }).otherwise(function(error){
            reject(error)
        });
    })
    
}
//向场景中添加3Dtiles
export const creat3DTileset = function(viewer,url,latlngheigt){
    var nonClassificationTileset = new Cesium3DTileset({
        url: url,
        show: true
    });
    nonClassificationTileset.readyPromise.then(function(tileset) {
        if(latlngheigt.lng != 0){
            update3dtilesMaxtrix(tileset,{
                tx: latlngheigt.lng,  //模型中心X轴坐标（经度，单位：十进制度）
                ty: latlngheigt.lat,  //模型中心Y轴坐标（纬度，单位：十进制度）
                tz: latlngheigt.height,    //模型中心Z轴坐标（高程，单位：米）
                rx: latlngheigt.roll || 0,    //X轴（经度）方向旋转角度（单位：度）
                ry: latlngheigt.pitch,    //Y轴（纬度）方向旋转角度（单位：度）
                rz: latlngheigt.heading,     //Z轴（高程）方向旋转角度（单位：度）
                scale:latlngheigt.scale
            })
        }
        
        viewer.scene.primitives.add(tileset);
        viewer.entities.add({
            id:latlngheigt.id,
            position: Cartesian3.fromDegrees(latlngheigt.lng, latlngheigt.lat,latlngheigt.height+20),
            // position: positions[positions.length - 1],
            point: {
                pixelSize: 5,
                color: Cesium.Color.RED,
                outlineColor: Cesium.Color.WHITE,
                disableDepthTestDistance:Number.POSITIVE_INFINITY,
                outlineWidth: 2,
            },
            label: {
                text: latlngheigt.title,
                font: '18px sans-serif',
                fillColor: Cesium.Color.GOLD,
                style: Cesium.LabelStyle.FILL_AND_OUTLINE,
                disableDepthTestDistance:Number.POSITIVE_INFINITY,
                outlineWidth: 2,
                verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                pixelOffset: new Cesium.Cartesian2(20, -20),
            }
        });
        // viewer.zoomTo(tileset)
        // viewer.flyTo(tileset,{
        //     maximumHeight:0,
        //     offset : {
        //         heading : Cesium.Math.toRadians(0.0),
        //         pitch : Cesium.Math.toRadians(-45),
        //         range : 0
        //     }
        // });
        return tileset
    }).otherwise(function(error){
        //Display any errrors encountered while loading.
        var layer = layui.layer
        layer.msg(error.message);
        return null
    }); 
    return nonClassificationTileset

}

function update3dtilesMaxtrix(tileset,params) {

    //旋转

    var mx = Matrix3.fromRotationX(Math.toRadians(params.rx));

    var my = Matrix3.fromRotationY(Math.toRadians(params.ry));

    var mz = Matrix3.fromRotationZ(Math.toRadians(params.rz));

    var rotationX = Matrix4.fromRotationTranslation(mx);

    var rotationY = Matrix4.fromRotationTranslation(my);

    var rotationZ = Matrix4.fromRotationTranslation(mz);

    //平移

    var position = Cartesian3.fromDegrees(params.tx, params.ty, params.tz);

    var m = Transforms.eastNorthUpToFixedFrame(position);
    Matrix4.multiplyByUniformScale(m, params.scale, m);
    //旋转、平移矩阵相乘

    Matrix4.multiply(m, rotationX, m);

    Matrix4.multiply(m, rotationY, m);

    Matrix4.multiply(m, rotationZ, m);
  
    //赋值给tileset

    tileset._root.transform = m;

}
//向场景中添加点要素
export const creatBillboard = function(viewer,config){
    var entity = viewer.entities.add({
        name: "mark",
        position: config.Cartesian3, // Cesium.Cartesian3.fromDegrees(config.lng, config.lat,config.height),
        billboard: { //图标
            image: dragIconLight,
            width: 20,
            height: 20,
            heightReference : HeightReference.CLAMP_TO_GROUND,
            eyeOffset: new ConstantProperty(new Cartesian3(0, 0, -100000))
            // disableDepthTestDistance : Number.POSITIVE_INFINITY
            // heightReference: HeightReference.CLAMP_TO_GROUND
        },
    });
}